<template>
  <div class="main">
    <!-- 页面头部 -->
    <div class="page-header">
      <h1 class="page-title">车位租赁</h1>
    </div>

    <!-- 搜索栏 -->
    <div class="search-container">
      <el-input
        v-model="searchParams.keyword"
        placeholder="输入车牌号或合同编号"
        style="width: 280px;"
        clearable
        @keyup.enter="handleSearch"
      >
        <template #append>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
          </el-button>
        </template>
      </el-input>
      
      <el-button type="primary" @click="showAddContractDialog" style="margin-left: 10px;">
        添加合同
      </el-button>
    </div>

    <!-- 合同列表表格 -->
    <div v-loading="loading" class="table-container">
      <el-table
        ref="tableRef"
        :data="contractList"
        stripe
        border
        style="width: 100%"
      >
        <el-table-column prop="carNumber" label="车牌号" width="120" />
        <el-table-column prop="name" label="所属小区" width="120" />
        <el-table-column prop="spaceNo" label="车位号" width="100" />
        <el-table-column prop="tenantName" label="联系人" width="100" />
        <el-table-column prop="tenantPhone" label="联系电话" width="130" />
        <el-table-column prop="startDate" label="开始时间" width="140" />
        <el-table-column prop="endDate" label="到期时间" width="140" />
        <el-table-column label="合同状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.contractStatus)">{{ getStatusName(row.contractStatus) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="chargeStandardCount" label="收费标准" width="100" />
        <el-table-column prop="chargeStandards" label="收费金额" width="120" />
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleDetail(row.id)">详情</el-button>
            <el-button link type="primary" @click="handleEdit(row)">修改</el-button>
            <el-button link type="danger" @click="handleDelete(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.limit"
        :page-sizes="[5, 10, 20, 50]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加合同弹窗 -->
    <el-dialog
      v-model="addDialogVisible"
      :title="isEditMode ? '修改合同' : '添加合同'"
      width="600px"
      :close-on-click-modal="false"
    >
      <div class="add-contract-form">
        <div class="form-section">
          <h3>基本信息</h3>
          <div class="form-row">
            <el-form-item label="所属小区" :label-width="80">
              <el-select v-model="addContractForm.community" placeholder="请选择所属小区" :loading="communityLoading" clearable style="width: 100%;" @change="handleCommunityChange">
                <template #prefix>
                  <el-icon><Location /></el-icon>
                </template>
                <el-option
                  v-for="community in communityList"
                  :key="community.id"
                    :label="community.name"
                    :value="community.name"
                >
                  {{ community.name }}
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="已选小区" :label-width="80">
              <el-input v-model="addContractForm.community" placeholder="暂无选择" disabled style="width: 100%;" />
            </el-form-item>
            <el-form-item label="车位号" :label-width="80">
              <el-select 
                  v-model="addContractForm.spaceNo" 
                  placeholder="请先选择所属小区" 
                  :loading="parkingSpaceLoading" 
                  :disabled="!addContractForm.community"
                  clearable 
                  style="width: 100%;"
                  @change="handleSpaceChange"
                >
                  <el-option
                    v-for="space in parkingSpaceList"
                    :key="space.id"
                    :label="space.spaceNo"
                    :value="space.spaceNo"
                >
                  {{ space.spaceNo }}
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="已选车位号" :label-width="80">
              <el-input v-model="addContractForm.spaceNo" placeholder="暂无选择" disabled style="width: 100%;" />
            </el-form-item>
            <el-form-item label="收费金额" :label-width="80">
              <el-input v-model="addContractForm.amount" placeholder="请选择车位号" suffix-icon="el-icon-money" disabled />
            </el-form-item>
          </div>
          
          <div class="form-row">
            <el-form-item label="车辆号码" :label-width="80">
              <el-input v-model="addContractForm.carNumber" placeholder="请输入车辆号码" />
            </el-form-item>
            <el-form-item label="合同编号" :label-width="80">
              <el-input v-model="addContractForm.contractNumber" placeholder="请输入合同编号" />
            </el-form-item>
            <el-form-item label="租户" :label-width="80">
              <el-input v-model="addContractForm.tenantName" placeholder="请输入租户" />
            </el-form-item>
          </div>
          
          <div class="form-row">
            <el-form-item label="签订日期" :label-width="80">
              <el-date-picker v-model="addContractForm.signDate" type="date" placeholder="请选择签订日期" style="width: 100%;" />
            </el-form-item>
            <el-form-item label="联系人" :label-width="80">
              <el-input v-model="addContractForm.tenantContract" placeholder="请输入联系人" />
            </el-form-item>
            <el-form-item label="租赁方联系人" :label-width="100">
              <el-input v-model="addContractForm.tenantPhone" placeholder="请输入联系电话" />
            </el-form-item>
          </div>
          
          <div class="form-row">
            <el-form-item label="合同状态" :label-width="80">
              <div class="status-with-decoration">
                <el-select v-model="addContractForm.contractStatus" placeholder="请选择合同状态" style="width: 120px;">
                  <el-option label="进行中" value="1" />
                  <el-option label="已过期" value="0" />
                </el-select>
                <el-tag :type="getStatusTagType(parseInt(addContractForm.contractStatus))" style="margin-left: 10px;">
                  {{ getStatusName(parseInt(addContractForm.contractStatus)) }}
                </el-tag>
              </div>
            </el-form-item>
            <el-form-item label="租期(月)" :label-width="80">
              <el-input v-model="addContractForm.leaseTerm" type="number" placeholder="请输入租期" />
            </el-form-item>
            <el-form-item label="起租日期" :label-width="80">
              <el-date-picker v-model="addContractForm.startDate" type="date" placeholder="请选择起租日期" style="width: 100%;" />
            </el-form-item>
          </div>
          
          <div class="form-row">
            <el-form-item label="停租日期" :label-width="80">
              <el-date-picker v-model="addContractForm.endDate" type="date" placeholder="请选择停租日期" style="width: 100%;" />
            </el-form-item>
            <el-form-item label="保证金" :label-width="80">
              <el-input v-model="addContractForm.deposit" placeholder="请输入保证金" suffix-icon="el-icon-money" />
            </el-form-item>
            <el-form-item label="中介费" :label-width="80">
              <el-input v-model="addContractForm.agencyFee" placeholder="请输入中介费" suffix-icon="el-icon-money" />
            </el-form-item>
          </div>
          
          <div class="form-row">
            <el-form-item label="合同租金总额" :label-width="100">
              <el-input v-model="addContractForm.totalRent" placeholder="请输入合同租金总额" suffix-icon="el-icon-money" />
            </el-form-item>
          </div>
          
          <div class="form-row">
            <el-form-item label="备注" :label-width="80">
              <el-input v-model="addContractForm.remark" placeholder="请输入备注" type="textarea" rows="3" />
            </el-form-item>
          </div>
        </div>
      </div>
      
      <template #footer>
        <el-button @click="addDialogVisible = false">返回</el-button>
        <el-button type="primary" @click="saveContract">保存</el-button>
      </template>
    </el-dialog>
    
    <!-- 详情弹窗 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="合同详情"
      width="800px"
      :close-on-click-modal="false"
    >
      <div v-loading="detailLoading" class="detail-content">
        <div v-if="contractDetail" class="detail-form">
          <div class="form-row">
            <div class="form-item">
              <span class="label">合同编号：</span>
              <span class="value">{{ contractDetail.contractNumber }}</span>
            </div>
            <div class="form-item">
              <span class="label">车牌号：</span>
              <span class="value">{{ contractDetail.carNumber }}</span>
            </div>
            <div class="form-item">
              <span class="label">状态：</span>
              <span class="value">{{ contractDetail.contractStatus === 1 ? '进行中' : '已结束' }}</span>
            </div>
          </div>
          <div class="form-row">
            <div class="form-item">
              <span class="label">承租方：</span>
              <span class="value">{{ contractDetail.tenantName }}</span>
            </div>
            <div class="form-item">
              <span class="label">保证金：</span>
              <span class="value">{{ contractDetail.deposit }}元</span>
            </div>
            <div class="form-item">
              <span class="label">中介费：</span>
              <span class="value">{{ contractDetail.agencyFee }}元</span>
            </div>
          </div>
          <div class="form-row">
            <div class="form-item">
              <span class="label">开始时间：</span>
              <span class="value">{{ contractDetail.startDate }}</span>
            </div>
            <div class="form-item">
              <span class="label">结束时间：</span>
              <span class="value">{{ contractDetail.endDate }}</span>
            </div>
            <div class="form-item">
              <span class="label">总金额：</span>
              <span class="value">{{ contractDetail.totalRent }}元</span>
            </div>
          </div>
          <div class="form-row">
            <div class="form-item">
              <span class="label">签订日期：</span>
              <span class="value">{{ contractDetail.signDate }}</span>
            </div>
            <div class="form-item">
              <span class="label">合同备注：</span>
              <span class="value">{{ contractDetail.tenantContract || '-' }}</span>
            </div>
          </div>
          <div class="form-row">
            <div class="form-item">
              <span class="label">备注：</span>
              <span class="value">{{ contractDetail.remark || '-' }}</span>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElTable } from 'element-plus';
import { Search, Location } from '@element-plus/icons-vue';
import type { FormInstance } from 'element-plus';
import { getContractList, findContract, getParkingSpaceInfo, findCharges, addContract, updateContract, deleteContract } from '@/api/contract';
import type { ContractItem, ContractListParams, ApiResponse, ParkingSpaceInfo, FindChargesParams } from '@/api/contract';
import { getCommunityList } from '@/api/community';
import type { CommunityItem } from '@/api/community';

// 表格引用
const tableRef = ref<InstanceType<typeof ElTable>>();

// 加载状态
const loading = ref(false);
const detailLoading = ref(false);

// 搜索参数
const searchParams = reactive<ContractQueryParams>({
  keyword: '',
  page: 1,
  limit: 5
});

// 分页数据
const pagination = reactive({
  page: 1,
  limit: 5,
  total: 0
});

// 合同列表数据
const contractList = ref<ContractItem[]>([]);

// 详情弹窗
const detailDialogVisible = ref(false);
const contractDetail = ref<ContractItem | null>(null);

// 添加/编辑合同弹窗
const addDialogVisible = ref(false);
const isEditMode = ref(false);
const currentContractId = ref(0);
const addContractForm = reactive({
  community: '',
  spaceNo: '',
  amount: '',
  carNumber: '',
  contractNumber: '',
  tenantName: '',
  signDate: '',
  tenantContract: '',
  contractStatus: '1',
  leaseTerm: '',
  endDate: '',
  startDate: '',
  deposit: '',
  agencyFee: '',
  totalRent: '',
  remark: '',
  tenantPhone: ''
});

// 小区列表
const communityList = ref<CommunityItem[]>([]);
const communityLoading = ref(false);

// 车位列表
const parkingSpaceList = ref<ParkingSpaceInfo[]>([]);
const parkingSpaceLoading = ref(false);

// 获取合同列表
const fetchContractList = async () => {
  loading.value = true;
  try {
    const params = {
      page: pagination.page,
      limit: pagination.limit,
      query: searchParams.keyword // 搜索关键词已改名为query
    };
    const response = await getContractList(params);
    if (response.code === 0) {
      contractList.value = response.data?.list || [];
      pagination.total = response.data?.total || 0;
    } else {
      ElMessage.error(response.message || '获取合同列表失败');
    }
  } catch (error) {
    console.error('获取合同列表失败:', error);
    ElMessage.error('获取合同列表失败');
  } finally {
    loading.value = false;
  }
};

// 获取合同详情
const handleDetail = async (id: number) => {
  detailLoading.value = true;
  try {
    const response = await findContract(id);
    if (response.code === 0) {
      contractDetail.value = response.data;
      detailDialogVisible.value = true;
    } else {
      ElMessage.error(response.message || '获取合同详情失败');
    }
  } catch (error) {
    console.error('获取合同详情失败:', error);
    ElMessage.error('获取合同详情失败');
  } finally {
    detailLoading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  pagination.page = 1;
  fetchContractList();
};

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.limit = size;
  fetchContractList();
};

// 页码变化
const handleCurrentChange = (current: number) => {
  pagination.page = current;
  fetchContractList();
};

// 获取状态标签类型
const getStatusTagType = (status: number): string => {
  if (status === 0) return 'danger'; // 已过期
  if (status === 1) return 'success'; // 进行中
  return 'info';
};

// 获取状态名称
const getStatusName = (status: number): string => {
  if (status === 0) return '已过期';
  if (status === 1) return '进行中';
  return '未知';
};

// 获取小区列表
const fetchCommunityList = async () => {
  communityLoading.value = true;
  try {
    const response = await getCommunityList();
    if (response.code === 0) {
      communityList.value = response.data || [];
    } else {
      ElMessage.error(response.message || '获取小区列表失败');
    }
  } catch (error) {
    console.error('获取小区列表失败:', error);
    ElMessage.error('获取小区列表失败');
  } finally {
    communityLoading.value = false;
  }
};

// 根据小区ID获取车位列表
const fetchParkingSpaceList = async (cellId: number) => {
  if (!cellId) {
    parkingSpaceList.value = [];
    return;
  }
  
  parkingSpaceLoading.value = true;
  try {
    const response = await getParkingSpaceInfo(cellId);
    if (response.code === 0) {
      parkingSpaceList.value = response.data || [];
    } else {
      ElMessage.error(response.message || '获取车位列表失败');
    }
  } catch (error) {
    console.error('获取车位列表失败:', error);
    ElMessage.error('获取车位列表失败');
  } finally {
    parkingSpaceLoading.value = false;
  }
};

// 监听小区选择变化
const handleCommunityChange = () => {
  // 重置车位选择和收费金额
  addContractForm.spaceNo = '';
  addContractForm.amount = '';
  
  // 根据选择的小区名称查找对应的小区ID
  const selectedCommunity = communityList.value.find(community => community.name === addContractForm.community);
  if (selectedCommunity) {
    fetchParkingSpaceList(selectedCommunity.id);
  } else {
    parkingSpaceList.value = [];
  }
};

// 监听车位选择变化，调用findCharges获取收费金额
const handleSpaceChange = async () => {
  // 重置收费金额
  addContractForm.amount = '';
  
  // 获取选中的车位信息
  const selectedSpace = parkingSpaceList.value.find(space => space.spaceNo === addContractForm.spaceNo);
  if (!selectedSpace) return;
  
  // 调用findCharges方法获取收费金额
  try {
    const params: FindChargesParams = {
      spsId: selectedSpace.id,
      tenantId: 0 // 这里假设tenantId为0，实际应根据业务需求设置
    };
    
    const response = await findCharges(params);
    if (response.code === 0 && response.data && response.data.length > 0) {
      // 将所有收费标准用逗号连接显示
      addContractForm.amount = response.data.join('，');
    } else {
      ElMessage.warning(response.message || '获取收费金额失败');
    }
  } catch (error) {
    console.error('获取收费金额失败:', error);
    ElMessage.error('获取收费金额失败');
  }
};

// 显示添加合同弹窗
const showAddContractDialog = async () => {
  isEditMode.value = false;
  currentContractId.value = 0;
  // 重置表单
  Object.keys(addContractForm).forEach(key => {
    addContractForm[key as keyof typeof addContractForm] = '';
  });
  addContractForm.contractStatus = '1';
  
  // 获取小区列表
  await fetchCommunityList();
  
  addDialogVisible.value = true;
};

// 处理编辑合同
const handleEdit = async (row: ContractItem) => {
  isEditMode.value = true;
  currentContractId.value = row.id;
  detailLoading.value = true;
  
  try {
    // 先获取合同详情用于填充其他字段
    const response = await findContract(row.id);
    if (response.code === 0 && response.data) {
      const contractData = response.data;
      
      // 获取小区列表用于后续回显
      await fetchCommunityList();
      
      // 直接使用表格行数据填充关键字段（所属小区、车位号、收费金额）
      addContractForm.community = row.name || ''; // 使用表格行数据中的小区名称
      addContractForm.spaceNo = row.spaceNo || ''; // 使用表格行数据中的车位号
      addContractForm.amount = row.chargeStandards || ''; // 使用表格行数据中的收费金额
      
      // 其他字段仍使用API获取的数据填充
      addContractForm.carNumber = contractData.carNumber || '';
      addContractForm.contractNumber = contractData.contractNumber || '';
      addContractForm.tenantName = contractData.tenantName || '';
      addContractForm.signDate = contractData.signDate || '';
      addContractForm.tenantContract = contractData.tenantContract || '';
      addContractForm.contractStatus = String(contractData.contractStatus || '1');
      addContractForm.leaseTerm = String(contractData.leaseTerm || '');
      addContractForm.startDate = contractData.startDate || '';
      addContractForm.endDate = contractData.endDate || '';
      addContractForm.deposit = String(contractData.deposit || '');
      addContractForm.agencyFee = String(contractData.agencyFee || '');
      addContractForm.totalRent = String(contractData.totalRent || '');
      addContractForm.remark = contractData.remark || '';
      addContractForm.tenantPhone = contractData.tenantPhone || '';
      
      // 如果有小区信息，加载对应的车位列表
      if (addContractForm.community) {
        const selectedCommunity = communityList.value.find(community => community.name === addContractForm.community);
        if (selectedCommunity) {
          await fetchParkingSpaceList(selectedCommunity.id);
        }
      }
      
      // 显示弹窗
      addDialogVisible.value = true;
    } else {
      ElMessage.error(response.message || '获取合同详情失败');
    }
  } catch (error) {
    console.error('获取合同详情失败:', error);
    ElMessage.error('获取合同详情失败');
  } finally {
    detailLoading.value = false;
  }
};

// 删除合同
const handleDelete = async (id: number) => {
  try {
    const response = await deleteContract(id);
    if (response.code === 0) {
      ElMessage.success('合同删除成功');
      // 重新获取合同列表
      fetchContractList();
    } else {
      ElMessage.error(response.message || '合同删除失败');
    }
  } catch (error) {
    console.error('删除合同失败:', error);
    ElMessage.error('合同删除失败');
  }
};

// 保存合同（新增或修改）
const saveContract = async () => {
  // 这里可以添加表单验证逻辑
  try {
    // 获取选中的车位信息用于获取parkingSpaceId
    const selectedSpace = parkingSpaceList.value.find(space => space.spaceNo === addContractForm.spaceNo);
    
    // 格式化日期为ISO 8601格式 (yyyy-MM-dd'T'HH:mm:ss.SSS'Z')
    const formatDateToISO = (dateString: string): string | undefined => {
      if (!dateString) return undefined;
      const date = new Date(dateString);
      // 检查日期是否有效
      if (isNaN(date.getTime())) return undefined;
      return date.toISOString(); // 返回ISO 8601格式
    };
    
    // 构造符合接口要求的合同数据对象
    const contractData = {
      ...addContractForm,
      id: isEditMode.value ? currentContractId.value : undefined,
      parkingSpaceId: selectedSpace?.id || 0,
      // 确保数值类型字段正确转换
      leaseTerm: parseInt(addContractForm.leaseTerm) || 0,
      deposit: parseFloat(addContractForm.deposit) || 0,
      agencyFee: parseFloat(addContractForm.agencyFee) || 0,
      totalRent: parseFloat(addContractForm.totalRent) || 0,
      contractStatus: parseInt(addContractForm.contractStatus) || 0,
      // 日期字段转换为ISO 8601格式
      signDate: formatDateToISO(addContractForm.signDate),
      startDate: formatDateToISO(addContractForm.startDate),
      endDate: formatDateToISO(addContractForm.endDate)
    };
    
    // 根据是否为编辑模式调用不同的API
    const response = isEditMode.value 
      ? await updateContract(contractData) 
      : await addContract(contractData);
    
    if (response.code === 0) {
      ElMessage.success(isEditMode.value ? '合同修改成功' : '合同保存成功');
      addDialogVisible.value = false;
      
      // 重新获取合同列表
      fetchContractList();
    } else {
      ElMessage.error(response.message || (isEditMode.value ? '合同修改失败' : '合同保存失败'));
    }
  } catch (error) {
    console.error('保存合同失败:', error);
    ElMessage.error(isEditMode.value ? '合同修改失败' : '合同保存失败');
  }
};

// 页面挂载时获取数据
onMounted(() => {
  fetchContractList();
});
</script>

<style scoped>
.main {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.search-container {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.add-contract-form {
  padding: 10px 0;
}

.form-section {
  margin-bottom: 20px;
}

.form-section h3 {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 15px;
  color: #303133;
}

.add-contract-form .form-row {
  margin-bottom: 15px;
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.table-container {
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
}

.detail-content {
  padding: 20px 0;
}

.detail-form {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.form-row {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.form-item {
  display: flex;
  align-items: center;
  min-width: 200px;
}

.form-item .label {
  width: 100px;
  font-weight: 600;
  color: #303133;
  margin-right: 8px;
}

.form-item .value {
  color: #606266;
  flex: 1;
}

.status-with-decoration {
  display: flex;
  align-items: center;
}
</style>